package com.kingwang.demo.springsecuritytokendemo.utils;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * HTTP Servlet工具类
 *
 * @author King
 */
public class HttpServletUtils {
    private HttpServletUtils() {
        throw new IllegalStateException("Utility class");
    }

    public static void sendHttpStatusResponse(HttpServletResponse response, HttpStatus httpStatus) throws IOException {
        sendJsonContentResponse(response, httpStatus, null);
    }

    public static void sendJsonContentResponse(HttpServletResponse response, HttpStatus httpStatus, Object content) throws IOException {
        response.setStatus(httpStatus.value());

        if (content != null) {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());

            String body = JsonConvert.serializeObject(content);

            PrintWriter responseWriter = response.getWriter();
            responseWriter.write(body);
            responseWriter.flush();
        }

        response.flushBuffer();
    }
}
